package com.tensquare.user.controller;

import cn.hutool.core.util.StrUtil;
import com.tensquare.entity.Result;
import com.tensquare.entity.StatusCode;
import com.tensquare.user.pojo.User;
import com.tensquare.user.service.UserService;
import com.tensquare.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by WF on 2020/12/21 16:11
 */
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private HttpServletRequest request;
    //1.发送手机验证码
    @PostMapping("sendsms/{mobile}")
    public Result sendValidCode(@PathVariable String mobile){
        userService.sendMessage(mobile);
        System.out.println("hello");
        return new Result(true, StatusCode.OK,"发送消息成功！");
    }

    //2.用户注册
    @PostMapping("register/{code}")
    public Result add(@PathVariable String code, @RequestBody User user){
        boolean b = userService.add(user,code);
        if(b){
            return new Result(true, StatusCode.OK,"用户注册成功！");
        }
        return new Result(false, StatusCode.ERROR,"用户注册失败！");

    }

    //3.用户登录
    @PostMapping("login")
    public Result login(@RequestBody User user){
        //3.1)查询用户是否存在
        User loginUser = userService.findUser(user);
        //3.2)如果存在，就返回
        if(loginUser != null){
            //3.2.1)创建token
            String token = jwtUtil.createJwt(loginUser.getId(), loginUser.getNickname(), "user");
            //3.2.2)定义map放token
            Map map = new HashMap<>();
            map.put("name",loginUser.getNickname());
            map.put("token",token);
            return new Result(true, StatusCode.OK,"登录成功！",map);
        }
        return new Result(false, StatusCode.ERROR,"登录失败！");
    }

    //4.删除用户
    @DeleteMapping("{userId}")
    public Result delete(@PathVariable String userId){
        //4.1)从请求作用域中得到值
        Claims claims = (Claims) request.getAttribute("claims");
        //4.2)判断是否有值
        if(claims != null){
            //4.2.1)得到用户的角色
            String role = (String) claims.get("role");
            //4.2.2)判断是否是管理员
            if(StrUtil.isNotBlank(role) && "admin".equals(role)){
                userService.deleteById(userId);
                return  new Result(true,StatusCode.OK,"删除用户成功！");
            }
        }
        return  new Result(false,StatusCode.ACCESSERROR,"无权访问！");
    }

    //5.增加关注数
    @PostMapping("incfollow/{userid}/{x}")
    public void incFollow(@PathVariable String userid, @PathVariable int x){
        userService.incFollow(userid,x);
    }

    //6.增加粉丝数
    @PostMapping("incfans/{userid}/{x}")
    public void incFans(@PathVariable String userid, @PathVariable int x){
        userService.incfans(userid,x);
    }

}
